package com.example;

import com.example.job.JobUtils;
import com.example.utils.*;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.TimeoutHandler;

import java.io.ByteArrayOutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Classname Application
 * @Description TODO
 * @Date 2022/7/26 11:23
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class Application extends AbstractVerticle {

    private static Class<?> clazz=null;


    public static void main(String[] args) throws Exception{
        Application.Run(Application.class);
    }

    public static void Run(Class<?> clazz){
        Vertx vertx = Vertx.vertx();
        Application.clazz=clazz;
        // 直接部署一个vertx程序
        vertx.deployVerticle(new Application());
    }

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        if(clazz == null){
            clazz=this.getClass();
        }
        Set<String> allowedHeaders = new HashSet<>();
        allowedHeaders.add("x-requested-with");
        allowedHeaders.add("Access-Control-Allow-Origin");
        allowedHeaders.add("Access-Control-Allow-Headers");
        allowedHeaders.add("origin");
        allowedHeaders.add("Content-Type");
        allowedHeaders.add("Authorization");
        allowedHeaders.add("accept");
        allowedHeaders.add("X-PINGARUNER");
        Set<HttpMethod> allowedMethods = new HashSet<>();
        allowedMethods.add(HttpMethod.GET);
        allowedMethods.add(HttpMethod.POST);
        allowedMethods.add(HttpMethod.OPTIONS);
        allowedMethods.add(HttpMethod.DELETE);
        allowedMethods.add(HttpMethod.PATCH);
        allowedMethods.add(HttpMethod.PUT);


        Router router = Router.router(vertx);
        //设置超时
        router.route().handler(TimeoutHandler.create(8000));
        //开启跨域
        router.route().handler(CorsHandler.create("*").allowedHeaders(allowedHeaders).allowedMethods(allowedMethods));
        ObjectMaps.setAutuWirdemap(Vertx.class.getName(),vertx);
        ClazzScanUtils.searchClass(Application.clazz);
        ClazzScanUtils.scanClass(Application.clazz);

        List<Class<?>> cls=ClazzScanUtils.getClassPaths();
        ObjectMaps.createClazzList(cls,router);


        String path= PathUtils.getPath();
        router.route("/upload/jar")
                .handler(BodyHandler.create().setUploadsDirectory(path).setBodyLimit(100000000));
        router.post("/upload/jar").handler(e->{

            for(FileUpload f : e.fileUploads()) {
                Buffer buffer=Buffer.buffer();
                vertx.fileSystem().writeFile(f.uploadedFileName(),buffer);

                byte[] bytes=buffer.getBytes();
                System.out.println(bytes.length+"这是长度");
                System.out.println(f.uploadedFileName());
                vertx.fileSystem().move(f.uploadedFileName(), "./"+ f.fileName(), res->{
                    if(res.succeeded()) {
                        System.out.println(f.fileName());
                        System.out.println(f.uploadedFileName());
                        System.out.println(f.name());

                        System.out.println("upload success.");
                    } else {
                        res.cause().printStackTrace();
                    }
                });
            }
            e.response().end();
        });



        router.route("/my/uploadimage")
                .handler(BodyHandler.create().setUploadsDirectory("mines").setBodyLimit(1000000000))
                .handler(StaticHandler.create().setWebRoot("mines").setCachingEnabled(false).setDirectoryListing(false));


        router.route("/my/uploadimage").handler(ctx->{
            ctx.response().setChunked(true);

            for(FileUpload f : ctx.fileUploads()) {
                Buffer buffer=Buffer.buffer();
                vertx.fileSystem().writeFile(f.uploadedFileName(),buffer);
                byte[] bytes=buffer.getBytes();


                vertx.fileSystem().move(f.uploadedFileName(), "./mines/"+ f.fileName(), res->{
                    if(res.succeeded()) {
                        System.out.println(f.fileName());
                        System.out.println(f.uploadedFileName());
                        System.out.println(f.name());

                        System.out.println("upload success.");
                    } else {
                        res.cause().printStackTrace();
                    }
                });
            }
            ctx.response().end();
        });

        String port= PropertiesUtils.getProperty("port");

        vertx.createHttpServer()
                .requestHandler(router)
                .listen(Integer.parseInt(port))
                .onSuccess(server ->
                        System.out.println(
                                "HTTP server started on port " + server.actualPort()
                        )
                );
        FileWatcher.init();

        //初始化
        JobUtils.JobInit();


    }

}
